package models

import (
	"fmt"
	"log"
	"rongyy/src/app"
)

type SupplierModel struct {
	BaseModel      `xorm:"extends"`
	Type           string `json:"type"` // 类型
	Name           string `json:"name"`
	Status         string `json:"status"`     // 0 待支付，1挂号成功，-1退号，-2退号退费
	UpdatedBy      string `json:"updated_by"` //callback updated by
	IdNo           string `json:"id_no"`
	Occupation     string `json:"occupation"`
	CompanyName    string `json:"company_name"`
	Corporation    string `json:"corporation"`
	CompanyAddress string `json:"company_address"`
	Tel            string `json:"tel"`
	Remark         string `json:"remark"`
	Openid         string `json:"openid" xorm:"openid"`
	Mobile         string `json:"mobile"`
	AcceptDept     string `json:"accept_dept"`
	IdImg          string `json:"id_img"`
	LjclsImg       string `json:"ljcls_img"`
	RecordImg      string `json:"record_img"`
	AuthImg        string `json:"auth_img"`
	Purpose        string `json:"purpose"`
	Business       string `json:"business"`
	Sn             string `json:"sn"`
	Date           string `json:"date"`
}

type ReqSupplier struct {
	Limit      int    `json:"limit"`
	Offset     int    `json:"offset"`
	IdNo       string `json:"id_no"`
	Name       string `json:"name"`
	Status     string `json:"status"`
	Openid     string `json:"openid"`
	Type       string `json:"type"`
	AcceptDept string `json:"accept_dept"`
}

func (rm *SupplierModel) TableName() string {
	return "supplier_apply"
}

func (rm *SupplierModel) Create(req *SupplierModel) error {
	req.Status = "pending"
	_, err := app.DB().Insert(req)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (rm *SupplierModel) GetById(id int64) (*SupplierModel, error) {
	ncm := &SupplierModel{}
	has, err := app.DB().ID(id).Get(ncm)
	if !has {
		return nil, fmt.Errorf("不存在")
	}
	if err != nil {
		return nil, err
	}
	return ncm, nil
}

func (rm *SupplierModel) Query(req *ReqSupplier) ([]SupplierModel, int64, error) {
	cms := make([]SupplierModel, 0)
	//local, _ := time.LoadLocation("Asia/Shanghai")
	//t := time.Now().In(local).Format("2006-01-02 15:04:05")
	fmt.Println(req.Status != "")

	s := app.DB().Table("supplier_apply")
	if req.Openid != "" {
		pid := fmt.Sprintf("%%%s%%", req.Openid)
		s.Where("openid like ?", pid)
	}
	if req.Name != "" {
		pid := fmt.Sprintf("%%%s%%", req.Name)
		s.Where("name like ?", pid)
	}

	if req.Type != "" {
		s.Where("type = ?", req.Type)
	}

	if req.AcceptDept != "" {
		pid := fmt.Sprintf("%%%s%%", req.AcceptDept)
		s.Where("accept_dept like ?", pid)
	}

	if req.Status != "" {
		s.Where("status = ?", req.Status)
	}

	total, err := s.Limit(req.Limit, req.Offset).Desc("created_at").FindAndCount(&cms)
	if err != nil {
		return nil, 0, err
	}
	return cms, total, err
}

func (rm *SupplierModel) UpdateId() error {
	s := app.DB()
	_, err := s.ID(rm.Id).Update(rm)
	if err != nil {
		return err
	}
	return nil
}
